package com.sec.etech.org.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.sec.etech.bpm.constant.DBConstant;
import com.sec.etech.org.model.OrgUser;
import org.openbpm.base.core.util.AppUtil;
import org.openbpm.org.api.model.IUser;
import org.openbpm.sys.service.impl.SysDataSourceService;
import org.openbpm.sys.util.ContextUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EtechUserUtil {

    public static EtechUserService getEtechUserService(){
        return (EtechUserService)AppUtil.getBean("etechUserService");
    }

    public static EtechGroupService getEtechGroupService(){
        return (EtechGroupService)AppUtil.getBean("etechGroupService");
    }

    public static IUser getUserById(Long id){
        return getUserById(String.valueOf(id));
    }
    public static IUser getUserById(String id){
        IUser user = getEtechUserService().getUserById(id);
        return user;
    }

    public static IUser getUserAdmin(){
        return getEtechUserService().getUserByAccount("admin");
    }

    public static IUser getUserByAccount(String account){
        return getEtechUserService().getUserByAccount(account);
    }

    public static String getUserNameById(Long id){
        return getUserNameById(String.valueOf(id));
    }
    public static String getUserNameById(String id){
        IUser user = getUserById(id);
        if(user!=null){
            return user.getFullname();
        }
        return "";
    }
    public static String getUserAccountById(String id){
        IUser user = getUserById(id);
        if(user!=null){
            return user.getAccount();
        }
        return "";
    }

    public static String getUserMailByIdOrAccount(String key){
        return getEtechUserService().getUserMailByIdOrAccount(key);
    }

    public static List<String> getUserIdsByRoleCode(String roleCode){
        return getEtechUserService().getUserIdsByRoleCode(roleCode);
    }

    public static List<IUser> getUsersByRoleCode(String roleCode){
        List<IUser> users = new ArrayList<>();
        List<String> userIds = getUserIdsByRoleCode(roleCode);
        if(userIds!=null){
            for(String userId: userIds){
               IUser user = getUserById(userId);
               if(user!=null){
                   users.add(user);
               }
            }
        }
        return users;
    }

    public static List<String> getAllDprtIdsByDprtId(String dprtId){
        return getEtechGroupService().getAllDprtIdsByDprtId(dprtId);
    }

    public static boolean checkUserHasRole(String roleCode) {
        String userId = ContextUtil.getCurrentUserId();
        List<String> userIds = getUserIdsByRoleCode(roleCode);
        if(userIds!=null && userIds.contains(userId)){
            return true;
        }
        return false;
    }

    /**
     * 根据部门班组id，查询同级以及下级部门的所有用户ID  发邮件使用
     * @param dprtId
     * @return
     */
    public static List<String> getAllUserIdsByDprtId(String dprtId) {
        List<String> userIds = new ArrayList<>();
        List<String> groupIds = getAllDprtIdsByDprtId(dprtId);
        List<IUser> userList = getEtechUserService().getUsersByGroupIds(groupIds);
        if (userList != null && userList.size() > 0) {
            for (IUser u : userList) {
                userIds.add(u.getUserId());
            }
        }
        return userIds;
    }

    /**
     * 根据部门班组id，只查询该部门的用户
     * @param dprtId
     * @return
     */
    public static List<String> getUserIdsByDprtId(String dprtId) {
        List<String> userIds = new ArrayList<>();
        ArrayList<String> groupIdList = new ArrayList<>();
        groupIdList.add(dprtId);
        List<IUser> userList = getEtechUserService().getUsersByGroupIds(groupIdList);
        if (userList != null && userList.size() > 0) {
            for (IUser u : userList) {
                userIds.add(u.getUserId());
            }
        }
        return userIds;
    }

    /**
     * 据设计科室获取计划班组长
     *
     * @param designDepartId 设计科室 id
     * @return
     */
    public static List<String> getManagerIdListByDesignDepartId(Long designDepartId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from proj_plantask_z_designdprt_managers where active = 1 and designdprtid=" + designDepartId;
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);
        return userIdList;
    }

    /**
     * 据科室获取计划班组长
     *
     * @param departId
     * @return
     */
    public static List<String> getManagerIdListByDepartId(Long departId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select m.uid from proj_plantask_z_designdprt_managers m,proj_plantask_z_designdprt d where d.designdprtid=m.designdprtid and m.active = 1 and d.dprtid=" + departId;
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);
        return userIdList;
    }

    /**
     * 据设计科室获取【SAM负责人】
     *
     * @param designDepartId 设计科室 id
     * @return
     */
    public static List<String> getSamManagerIdListByDesignDepartId(Long designDepartId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select uid from proj_plantask_z_designdprt_sam_manager where active = 1 and designdprt_id=" + designDepartId + " ORDER BY orderby";
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);
        return userIdList;
    }

    /**
     * 据科室获取【SAM负责人】
     *
     * @param departId 科室 id
     * @return
     */
    public static List<String> getSamManagerIdListByDepartId(Long departId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "select m.uid from proj_plantask_z_designdprt_sam_manager m,proj_plantask_z_designdprt d where d.designdprtid=m.designdprt_id and m.active = 1 and d.dprtid=" + departId + " ORDER BY orderby";
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);
        return userIdList;
    }


    /**
     * 据设计科室获取【RD 负责人】
     *
     * @param designDepartId 设计科室 id
     * @return
     */
    public static List<String> getRandsManagerIdListByDesignDepartId(Long designDepartId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "SELECT rands_manager FROM `proj_plantask_z_designdprt`  where  designdprt_id=" + designDepartId;
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);

        if (userIdList != null && userIdList.size() > 0) {
            String ids = userIdList.get(0);
            if (!StrUtil.isBlankOrUndefined(ids)) {
                return Arrays.asList(ids.split(","));

            }
        }
        return new ArrayList<>();
    }

    /**
     * 据科室获取【RD 负责人】
     *
     * @param departId 科室 id
     * @return
     */
    public static List<String> getRandsManagerIdListByDepartId(Long departId) {
        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);
        String sql = "SELECT rands_manager FROM `proj_plantask_z_designdprt`  where dprtid=" + departId;
        List<String> userIdList = jdbcTemplate.queryForList(sql, String.class);

        if (userIdList != null && userIdList.size() > 0) {
            String ids = userIdList.get(0);
            if (!StrUtil.isBlankOrUndefined(ids)) {
                return Arrays.asList(ids.split(","));

            }
        }
        return new ArrayList<>();
    }


    /**
     * 据 uid 获取所在科室的部门主管 managerIdList
     *
     * @param uid 用户 id
     * @return
     */
    public static List<String> getManagerIdList(String uid) {
        if (uid == null) {
            throw new RuntimeException("@getManagerIdList 参数为 uid = null ");
        }

        List<OrgUser> managerList = getManagerList(new ArrayList() {
            {
                add(uid);
            }
        });

        ArrayList<String> managerIdList = new ArrayList<>();
        for (OrgUser item : managerList) {
            managerIdList.add(item.getId());
        }

        return managerIdList;

    }

    /**
     * 据 uidList 获取所在科室的部门主管 List<OrgUser>
     *
     * @param uid 用户 id
     * @return
     */
    public static List<OrgUser> getManagerList(List<String> uidList) {
        if (uidList == null) {
            throw new RuntimeException("@getManagerList 参数为 uidList = null ");
        }

        if (CollUtil.isEmpty(uidList)) {
            throw new RuntimeException("@getManagerList 参数为 uidList = 空 ");

        }

        SysDataSourceService sysDataSourceService = AppUtil.getBean(SysDataSourceService.class);
        JdbcTemplate jdbcTemplate = sysDataSourceService.getJdbcTemplateByKey(DBConstant.PLAN_DB);

        String sql = "SELECT\n" +
                "\ta.uid AS `id`,\n" +
                "\tb.fullname_  AS `fullname`\n" +
                "FROM\n" +
                "\t`wss_dprt_manager`  as a\n" +
                "\tLEFT JOIN org_user as b ON a.uid = b.id_ \n" +
                "WHERE\n" +
                "\ta.active = 1 \n" +
                "\tAND dprtid IN ( \n" +
                "\t\tSELECT group_id_ FROM `org_relation` WHERE type_ = 'groupUser' AND user_id_ IN ({}) GROUP BY group_id_ \n" +
                "\t) \n" +
                "GROUP BY\n" +
                "\tuid";

        List<OrgUser> orgUserList = jdbcTemplate.query(
                StrUtil.format(sql, "'" + String.join("','", uidList) + "'"),
                new BeanPropertyRowMapper<OrgUser>(OrgUser.class)
        );

        return orgUserList;

    }

}
